<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="handle-box">
          <div class="input-box">
            <el-input
              v-model="searchForm.company"
              placeholder="请输入公司名称"
              class="input-with-select mr20"
              @keyup.enter.native="getList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
            <el-input
              v-model="searchForm.company_short"
              placeholder="请输入公司简称"
              class="input-with-select mr20"
              @keyup.enter.native="getList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
            <el-input
              v-model="searchForm.user_name"
              placeholder="请输入联系人姓名"
              class="input-with-select mr20"
              @keyup.enter.native="getList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
            <el-input
              v-model="searchForm.user_phone"
              placeholder="请输入联系人电话"
              class="input-with-select mr20"
              @keyup.enter.native="getList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
            <el-input
              v-model="searchForm.area_name"
              placeholder="请输入地区"
              class="input-with-select mr20"
              @keyup.enter.native="getList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
          </div>
          <div>
            <el-button type="primary" icon="el-icon-refresh" @click="getList" class="mr20">刷新</el-button>
            <el-button type="primary" @click="handleAdd">添加</el-button>
          </div>
        </div>
      </div>
      <el-table v-loading="listLoading" :data="tableData.data" style="width: 100%" size="small" class="mt25">
        <el-table-column prop="id" label="ID" min-width="60" />
        <el-table-column prop="company" label="公司名称" min-width="150" />
        <el-table-column prop="company_short" label="公司简称" min-width="120" />
        <el-table-column prop="user_name" label="联系人" min-width="100" />
        <el-table-column prop="user_phone" label="联系电话" min-width="120" />
        <el-table-column prop="area_name" label="地区" min-width="120" />
        <!--        <el-table-column-->
        <!--          prop="status"-->
        <!--          label="状态"-->
        <!--          min-width="80"-->
        <!--        >-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-switch-->
        <!--              v-model="scope.row.status"-->
        <!--              :active-value="1"-->
        <!--              :inactive-value="0"-->
        <!--              active-color="#13ce66"-->
        <!--              inactive-color="#ff4949"-->
        <!--              @change="onChangeDealerStatus(scope.row)"-->
        <!--            ></el-switch>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="add_time" label="添加时间" min-width="150" />
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
            <!--            <el-button-->
            <!--              type="primary"-->
            <!--              size="small"-->
            <!--              @click="handleView(scope.row)"-->
            <!--            >-->
            <!--              查看-->
            <!--            </el-button>-->
            <el-button type="danger" size="small" @click="handleDelete(scope.row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[10, 20, 30, 40]"
          :page-size="searchForm.limit"
          :current-page="searchForm.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑经销商弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
      <el-form ref="dealerForm" :model="dealerForm" :rules="rules" label-width="120px" class="dealerForm">
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="dealerForm.company" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司简称" prop="company_short">
          <el-input v-model="dealerForm.company_short" placeholder="请输入公司简称" />
        </el-form-item>
        <el-form-item label="联系人" prop="user_name">
          <el-input v-model="dealerForm.user_name" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="user_phone">
          <el-input 
            v-model="dealerForm.user_phone" 
            placeholder="请输入联系人电话" 
            maxlength="11"
            oninput="value=value.replace(/[^0-9]/g,'')"
          />
        </el-form-item>
        <!--        <el-form-item label="地区" prop="area_name">-->
        <!--          <el-input v-model="dealerForm.area_name" placeholder="请输入地区" />-->
        <!--        </el-form-item>-->
        <el-form-item label="省市区选择" prop="city">
          <div class="acea-row">
            <el-select
              v-model="dealerForm.province"
              placeholder="请选择省份"
              @change="getCity"
              style="width: 32%; margin-right: 2%"
            >
              <el-option
                v-for="item in provinceList"
                :key="item.city_id"
                :label="item.label"
                :value="item.city_id"
              ></el-option>
            </el-select>
            <el-select
              v-model="dealerForm.city"
              placeholder="请选择城市"
              @change="getDistrict"
              style="width: 32%; margin-right: 2%"
            >
              <el-option
                v-for="item in cityList"
                :key="item.city_id"
                :label="item.label"
                :value="item.city_id"
              ></el-option>
            </el-select>
            <el-select v-model="dealerForm.area" placeholder="请选择区域" style="width: 32%">
              <el-option
                v-for="item in districtList"
                :key="item.city_id"
                :label="item.label"
                :value="item.city_id"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDealer">确定</el-button>
      </span>
    </el-dialog>

    <!-- 经销商详情弹窗 -->
    <el-dialog title="经销商详情" :visible.sync="detailVisible" width="700px">
      <div v-if="dealerDetail" class="dealer-detail">
        <div class="detail-item">
          <span class="label">ID:</span>
          <span class="value">{{ dealerDetail.id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">公司名称:</span>
          <span class="value">{{ dealerDetail.company }}</span>
        </div>
        <div class="detail-item">
          <span class="label">公司简称:</span>
          <span class="value">{{ dealerDetail.company_short }}</span>
        </div>
        <div class="detail-item">
          <span class="label">联系人:</span>
          <span class="value">{{ dealerDetail.user_name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">联系电话:</span>
          <span class="value">{{ dealerDetail.user_phone }}</span>
        </div>
        <div class="detail-item">
          <span class="label">地区:</span>
          <span class="value">{{ dealerDetail.area_name }}</span>
        </div>
        <!--        <div class="detail-item">-->
        <!--          <span class="label">状态:</span>-->
        <!--          <span class="value">-->
        <!--            <el-tag :type="dealerDetail.status === 1 ? 'success' : 'danger'">-->
        <!--              {{ dealerDetail.status === 1 ? '启用' : '禁用' }}-->
        <!--            </el-tag>-->
        <!--          </span>-->
        <!--        </div>-->
        <div class="detail-item">
          <span class="label">添加时间:</span>
          <span class="value">{{ dealerDetail.add_time }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDealerList,
  addDealer,
  updateDealer,
  getDealerDetail,
  changeDealerStatus,
  deleteDealer,
  editDealer,
} from '@/api/dealer';
import { cityListApi, templatesCityListApi } from '@/api/setting';
import { mapState } from 'vuex';

export default {
  name: 'DealerIndex',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        company: '',
        company_short: '',
        user_name: '',
        user_phone: '',
        area_name: '',
      },
      listLoading: false,
      tableData: {
        data: [],
        total: 0,
      },
      dialogVisible: false,
      detailVisible: false,
      dialogTitle: '添加经销商',
      dealerForm: {
        id: 0,
        company: '',
        company_short: '',
        user_name: '',
        user_phone: '',
        area_name: '',
        province: '',
        city: '',
        area: '',
      },
      dealerDetail: null,
      // 省市区数据
      provinceList: [],
      cityList: [],
      districtList: [],
      rules: {
        company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        company_short: [{ required: true, message: '请输入公司简称', trigger: 'blur' }],
        user_name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
        user_phone: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { 
            pattern: /^1[3-9]\d{9}$/, 
            message: '请输入正确的11位手机号码', 
            trigger: 'blur' 
          },
          {
            len: 11,
            message: '手机号码必须是11位数字',
            trigger: 'blur'
          }
        ],
        province: [{ required: true, message: '请选择省份', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        area: [{ required: true, message: '请选择区域', trigger: 'change' }],
      },
    };
  },
  computed: {
    ...mapState('app', ['pageLimit']),
  },
  mounted() {
    this.getList();
    this.getProvinceList();
  },
  methods: {
    // 获取列表
    getList() {
      this.listLoading = true;
      getDealerList(this.searchForm)
        .then((res) => {
          if (res.status === 200) {
            this.tableData.data = res.data.list || [];
            this.tableData.total = res.data.count || 0;
          } else {
            this.$message.error(res.msg || '获取数据失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取数据失败');
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 获取省份列表
    getProvinceList() {
      cityListApi(0)
        .then((res) => {
          this.provinceList = res.data || [];
        })
        .catch((err) => {
          this.$message.error('获取省份列表失败');
        });
    },

    // 获取城市列表
    getCity() {
      if (!this.dealerForm.province) return;

      // 清空区域
      this.dealerForm.city = '';
      this.dealerForm.area = '';
      this.districtList = [];

      cityListApi(this.dealerForm.province)
        .then((res) => {
          this.cityList = res.data || [];
        })
        .catch((err) => {
          this.$message.error('获取城市列表失败');
        });
    },

    // 获取区域列表
    getDistrict() {
      if (!this.dealerForm.city) return;

      // 清空区域
      this.dealerForm.area = '';

      cityListApi(this.dealerForm.city)
        .then((res) => {
          this.districtList = res.data || [];
        })
        .catch((err) => {
          this.$message.error('获取区域列表失败');
        });
    },

    // 切换分页
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },

    // 切换每页显示条数
    handleSizeChange(val) {
      this.searchForm.limit = val;
      this.getList();
    },

    // 添加经销商
    handleAdd() {
      this.dialogTitle = '添加经销商';
      this.dealerForm = {
        id: 0,
        company: '',
        company_short: '',
        user_name: '',
        user_phone: '',
        area_name: '',
        province: '',
        city: '',
        area: '',
      };
      this.cityList = [];
      this.districtList = [];
      this.dialogVisible = true;
    },

    // 编辑经销商
    handleEdit(row) {
      this.dialogTitle = '编辑经销商';
      // 直接使用row数据
      this.dealerForm = {
        id: row.id,
        company: row.company,
        company_short: row.company_short,
        user_name: row.user_name,
        user_phone: row.user_phone,
        area_name: row.area_name,
        province: row.province || '',
        city: row.city || '',
        area: row.area || '',
      };

      // 先获取省份数据
      cityListApi(0)
        .then((res) => {
          this.provinceList = res.data || [];

          // 如果有省份ID，获取城市数据
          if (this.dealerForm.province) {
            cityListApi(this.dealerForm.province)
              .then((res) => {
                this.cityList = res.data || [];

                // 如果有城市ID，获取区域数据
                if (this.dealerForm.city) {
                  cityListApi(this.dealerForm.city)
                    .then((res) => {
                      this.districtList = res.data || [];
                    })
                    .catch(() => {
                      this.$message.error('获取区域列表失败');
                    });
                }
              })
              .catch(() => {
                this.$message.error('获取城市列表失败');
              });
          }
        })
        .catch(() => {
          this.$message.error('获取省份列表失败');
        });

      this.dialogVisible = true;
    },

    // 查看经销商详情
    handleView(row) {
      this.dealerDetail = row;
      this.detailVisible = true;
      // getDealerDetail(row.id)
      //   .then(res => {
      //     if (res.status === 200) {
      //       this.dealerDetail = res.data;
      //       this.detailVisible = true;
      //     } else {
      //       this.$message.error(res.msg || '获取详情失败');
      //     }
      //   })
      //   .catch(err => {
      //     this.$message.error(err.msg || '获取详情失败');
      //   });
    },

    // 提交经销商表单
    submitDealer() {
      this.$refs.dealerForm.validate((valid) => {
        if (valid) {
          // 在提交前更新地区显示名称
          const provinceName = this.getAreaName(this.provinceList, this.dealerForm.province);
          const cityName = this.getAreaName(this.cityList, this.dealerForm.city);
          const areaName = this.getAreaName(this.districtList, this.dealerForm.area);

          // 更新显示的地区名称
          this.dealerForm.area_name =
            provinceName && cityName && areaName
              ? `${provinceName} ${cityName} ${areaName}`
              : this.dealerForm.area_name;

          // 根据是否有ID决定使用哪个API
          const request = this.dealerForm.id ? editDealer : addDealer;
          request(this.dealerForm)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success(this.dealerForm.id ? '编辑成功' : '添加成功');
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg || (this.dealerForm.id ? '编辑失败' : '添加失败'));
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || (this.dealerForm.id ? '编辑失败' : '添加失败'));
            });
        }
      });
    },

    // 获取地区名称
    getAreaName(list, id) {
      const item = list.find((item) => item.city_id === id);
      return item ? item.label : '';
    },

    // 删除经销商
    handleDelete(row) {
      this.$confirm('确定要删除该经销商吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 调用删除经销商接口
          deleteDealer(row.id)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('删除成功');
                this.getList(); // 刷新列表
              } else {
                this.$message.error(res.msg || '删除失败');
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || '删除失败');
            });
        })
        .catch(() => {
          this.$message.info('已取消操作');
        });
    },

    // 修改经销商状态
    onChangeDealerStatus(row) {
      changeDealerStatus(row.id, row.status)
        .then((res) => {
          if (res.status === 200) {
            this.$message.success('状态修改成功');
          } else {
            this.$message.error(res.msg || '状态修改失败');
            row.status = row.status === 0 ? 1 : 0; // 失败时恢复状态
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '状态修改失败');
          row.status = row.status === 0 ? 1 : 0; // 失败时恢复状态
        });
    },

    // 关闭弹窗
    handleClose() {
      this.$refs.dealerForm.resetFields();
      this.cityList = [];
      this.districtList = [];
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped lang="scss">
.input-with-select {
  width: 200px;
}
.handle-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.input-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.mr20 {
  margin-right: 20px;
  margin-bottom: 10px;
}
.mt25 {
  margin-top: 25px;
}
.block {
  margin-top: 20px;
  text-align: right;
}

.dealer-detail {
  padding: 10px;

  .detail-item {
    margin-bottom: 15px;
    display: flex;

    .label {
      width: 120px;
      color: #606266;
      text-align: right;
      padding-right: 12px;
      font-weight: 500;
    }

    .value {
      flex: 1;
      color: #333;
    }
  }
}
</style>
